package com.info.dpunified.web.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.validation.BindException;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
 
import com.info.dpunified.common.exception.DPUnifiedException;
import com.info.dpunified.dpgen.service.DefectUploadService;
import com.info.dpunified.web.model.DefectSubmission;
 
public class FileUploadController extends SimpleFormController{
 
    protected final Log logger = LogFactory.getLog(getClass());

	public FileUploadController(){
		//setCommandClass(DefectSubmission.class);
		//setCommandName("defectUploadForm");
	}
	
	/**
	 * @return the defectUploadService
	 */
	public DefectUploadService getDefectUploadService() {
		return defectUploadService;
	}

	/**
	 * @param defectUploadService the defectUploadService to set
	 */
	public void setDefectUploadService(DefectUploadService defectUploadService) {
		this.defectUploadService = defectUploadService;
	}

	private DefectUploadService defectUploadService;
 
	@Override
	protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception 
	{
 
        logger.info("finally here @ hello view with " + request.getParameter("cboMonth"));

		DefectSubmission file = (DefectSubmission)command;
 
		MultipartFile multipartFile = file.getDefectDump();
 
		String fileName="";
		 
		if(multipartFile!=null){
			fileName = multipartFile.getOriginalFilename();
			//do whatever you want
		}
		try
		{
			this.getDefectUploadService().insertDefects(multipartFile.getInputStream(),fileName);
		}
		catch(DPUnifiedException dpue)
		{
			dpue.printStackTrace();
			return new ModelAndView("/fileUploadFailure","fileName",fileName);
		}
		
		return new ModelAndView("/fileUploadSuccess","fileName",fileName);
	}
}